package com.image.service;

import com.image.util.DownloadUtil;
import com.image.util.HttpUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.jasper.tagplugins.jstl.core.ForEach;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class ImageService {

    public List<String> getImageUrl(String url, int page) throws IOException {
        //处理url,放入商品id和页数
        //获取商品id
        String goodId = url.substring(20,url.indexOf(".html"));
        url = "https://club.jd.com/discussion/getProductPageImageCommentList.action?productId="+goodId+"&page="+page;

        //传入url获取json数据
        String json = HttpUtils.doGet(url);

        //从json数据中取到imageUrl的集合
        JSONObject result = JSONObject.fromObject(json);
        JSONObject imgComments = (JSONObject) result.get("imgComments");
        JSONArray imgList = (JSONArray) imgComments.get("imgList");
        //获评论的条数
        int x = imgList.size();
        //从每一条评论中取imgUrl
        List<String> imageUrlList = new ArrayList<>();
        for (int i = 0;i < x; i++){
            JSONObject img = (JSONObject) imgList.get(i);
            String imageUrl = (String) img.get("imageUrl");
            imageUrlList.add(imageUrl);
        }

        return imageUrlList;
    }

    public void download(List<String> list,String downloadUrl) throws IOException {
        for(String url:list){
            String filename = UUID.randomUUID()+"";
            DownloadUtil.download("https:"+url,filename+".jpg",downloadUrl);
        }
    }

}
